package cn.edu.xjtu.TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Hydrion-QLz
 * @date 2022-06-14 10:20
 * @description TCP服务器端
 */

public class Server {
    public static void main(String[] args) throws IOException {
        Map<String, String> loginTable = new HashMap<>();
        int serverPort = 7777;
        ServerSocket serverSocket = new ServerSocket(serverPort);
        System.out.println("服务端启动成功");
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        while (true) {
            Socket socket = serverSocket.accept();
            Runnable runnable = () -> {
                BufferedReader br = null;
                BufferedWriter bw = null;
                try {
                    br = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                    bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
                    System.out.printf("成功建立新链接,客户端ip地址:%s ,客户端端口:%d\n", socket.getInetAddress().getHostAddress(), socket.getPort());
                    while (true) {
                        String mode = br.readLine();
                        String userName = br.readLine();
                        String password = br.readLine();
                        if (Integer.parseInt(mode) == 1) {
                            // 登录逻辑，判断账号密码
                            if (loginTable.getOrDefault(userName, "").equals(password)) {
                                bw.write("密码正确\n");
                            } else {
                                bw.write("用户名或密码有误\n");
                            }
                        } else {
                            // 注册逻辑
                            loginTable.put(userName, password);
                            bw.write("注册成功\n");
                        }
                        bw.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            };
            executorService.submit(runnable);
        }
    }
}
